package client

import (
	"context"
	"fmt"
	"io/ioutil"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/json"
	"k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/klog/v2"
)

func GetSecret(ns string) {
	clientSet, err := CreateClientSet()
	if err != nil {
		klog.Error(err)
	}
	opts := metav1.ListOptions{
		Watch: false,
	}
	cm, err := clientSet.CoreV1().Secrets(ns).List(context.TODO(), opts)
	for _, c := range cm.Items {
		klog.Info(c.Kind," ", c.Name," ", c.Namespace," ", c.ResourceVersion," ", c.CreationTimestamp)
	}
}

func CreateSecret(ns string, secretFile string) {
	clientSet, err := CreateClientSet()
	if err != nil {
		klog.Error(err)
	}
	secretClient := clientSet.CoreV1().Secrets(ns)
	var (
		data      []byte
		secret = &v1.Secret{}
	)
	if data, err = ioutil.ReadFile(secretFile); err != nil {
		fmt.Print(err)
	}
	if data, err = yaml.ToJSON(data); err != nil {
		return
	}
	if err = json.Unmarshal(data, secret); err != nil {
		return
	}
	secretName := secret.ObjectMeta.Name

	fmt.Println("secretName:", secretName)
	if _, err = secretClient.Get(context.TODO(), secretName, metav1.GetOptions{}); err != nil {
		if !errors.IsNotFound(err) {
			fmt.Println(err)
			return
		}
		if _, err = secretClient.Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
			fmt.Println(err)
			return
		}
	} else {
		if _, err = secretClient.Update(context.TODO(), secret, metav1.UpdateOptions{}); err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("secret creat success!")
	return
}
